package ndk.caro.activities;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;
import ndk.caro.activities.R;
import ndk.caro.bluetooths.BluetoothChatService;
import ndk.caro.gameplays.myCaroGame;
import ndk.caro.gameplays.myCaroGame.Player;
import ndk.caro.tools.myTool;
import ndk.caro.views.myCaroView;
import ndk.caro.views.myMenuView;

public class myCaroActivity extends Activity {

	// Bluetooth ://

	// Message types sent from the BluetoothChatService Handler
	public static final int MESSAGE_STATE_CHANGE = 1;
	public static final int MESSAGE_READ = 2;
	public static final int MESSAGE_WRITE = 3;
	public static final int MESSAGE_DEVICE_NAME = 4;
	public static final int MESSAGE_TOAST = 5;

	// Key names received from the BluetoothChatService Handler
	public static final String DEVICE_NAME = "device_name";
	public static final String TOAST = "toast";

	// Intent request codes
	private static final int REQUEST_CONNECT_DEVICE = 1;
	private static final int REQUEST_ENABLE_BT = 2;

	// Name of the connected device
	private String mConnectedDeviceName = null;
	// Local Bluetooth adapter
	private BluetoothAdapter mBluetoothAdapter = null;
	// Member object for the chat services
	private BluetoothChatService mChatService = null;

	private Point pointInput;

	public Point getPointInput() {
		return pointInput;
	}

	public void setPointInput(Point pointInput) {
		this.pointInput = pointInput;
	}

	private void ensureDiscoverable() {
		if (mBluetoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
			Intent discoverableIntent = new Intent(
					BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
			discoverableIntent.putExtra(
					BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
			startActivity(discoverableIntent);
		}
	}

	public void sendMessage(String message) {
		// Check that we're actually connected before trying anything
		if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
			Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT)
					.show();
			return;
		}

		// Check that there's actually something to send
		if (message.length() > 0) {
			// Get the message bytes and tell the BluetoothChatService to write
			byte[] send = message.getBytes();
			mChatService.write(send);

		}
	}

	@Override
	protected void onStart() {
		super.onStart();

		if (myCaroGame.getPlayer() == Player.BLUE) {

			// If BT is not on, request that it be enabled.
			// setupChat() will then be called during onActivityResult
			if (!mBluetoothAdapter.isEnabled()) {
				Intent enableIntent = new Intent(
						BluetoothAdapter.ACTION_REQUEST_ENABLE);
				startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
				// Otherwise, setup the chat session
			} else {
				if (mChatService == null) {
					setupChat();
				}
			}
		}
	}

	@Override
	protected synchronized void onPause() {
		super.onPause();
	}

	@Override
	protected synchronized void onResume() {
		super.onResume();

		if (myCaroGame.getPlayer() == Player.BLUE) {
			if (mChatService != null) {
				// Only if the state is STATE_NONE, do we know that we haven't
				// started already
				if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
					// Start the Bluetooth chat services
					mChatService.start();
				}
			}
		}
	}

	private void setupChat() {

		// Initialize the BluetoothChatService to perform bluetooth connections
		mChatService = new BluetoothChatService(this, mHandler);

	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		if (myCaroGame.getPlayer() == Player.BLUE) {
			// Stop the Bluetooth chat services
			if (mChatService != null) {
				mChatService.stop();
			}
		}
	}

	// The Handler that gets information back from the BluetoothChatService
	private final Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MESSAGE_STATE_CHANGE:
				switch (msg.arg1) {
				case BluetoothChatService.STATE_CONNECTED:
					Toast.makeText(
							myCaroActivity.this,
							getResources().getString(
									R.string.title_connected_to)
									+ mConnectedDeviceName, Toast.LENGTH_SHORT)
							.show();
					myCaroActivity.this.initNewGame();
					break;
				case BluetoothChatService.STATE_CONNECTING:
					Toast.makeText(
							myCaroActivity.this,
							getResources().getString(R.string.title_connecting),
							Toast.LENGTH_SHORT).show();

					break;
				case BluetoothChatService.STATE_LISTEN:
				case BluetoothChatService.STATE_NONE:
					Toast.makeText(
							myCaroActivity.this,
							getResources().getString(
									R.string.title_not_connected),
							Toast.LENGTH_SHORT).show();

					break;
				}
				break;
			case MESSAGE_WRITE:

				break;
			case MESSAGE_READ:
				try {
					byte[] readBuf = (byte[]) msg.obj;
					// construct a string from the valid bytes in the buffer
					String readMessage = new String(readBuf, 0, msg.arg1);
					if(readMessage != "") {
					myCaroActivity.this.mCaroView.mCaroGame
							.HandlePointToCaroView(myTool
									.returnPointFromString(readMessage));
					myCaroActivity.this.mCaroView.mCaroGame.bAllowTouchBluetooth = true;
					}
				} catch (Exception e) {
					Log.i("Error", e.toString());
				}
				break;
			case MESSAGE_DEVICE_NAME:
				// save the connected device's name
				mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
				Toast.makeText(getApplicationContext(),
						"Connected to " + mConnectedDeviceName,
						Toast.LENGTH_SHORT).show();
				break;
			case MESSAGE_TOAST:
				Toast.makeText(getApplicationContext(),
						msg.getData().getString(TOAST), Toast.LENGTH_SHORT)
						.show();
				break;
			}
		}
	};

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case REQUEST_CONNECT_DEVICE:
			// When DeviceListActivity returns with a device to connect
			if (resultCode == Activity.RESULT_OK) {
				// Get the device MAC address
				String address = data.getExtras().getString(
						myDeviceListActivity.EXTRA_DEVICE_ADDRESS);
				// Get the BLuetoothDevice object
				BluetoothDevice device = mBluetoothAdapter
						.getRemoteDevice(address);
				// Attempt to connect to the device
				mChatService.connect(device);
			}
			break;
		case REQUEST_ENABLE_BT:
			// When the request to enable Bluetooth returns
			if (resultCode == Activity.RESULT_OK) {
				// Bluetooth is now enabled, so set up a chat session
				setupChat();
			} else {
				// User did not enable Bluetooth or an error occured
				Toast.makeText(this, R.string.bt_not_enabled_leaving,
						Toast.LENGTH_SHORT).show();
				finish();
			}
		}
	}

	// Non Bluetooth :
	public myCaroView mCaroView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		if(myCaroGame.getPlayer() != Player.BLUE ) {
			getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
			 WindowManager.LayoutParams.FLAG_FULLSCREEN);
		}
			setContentView(R.layout.caro_layout);
		

		mCaroView = (myCaroView) findViewById(R.id.mCaroView);

		if (myCaroGame.getPlayer() == Player.BLUE) {
			myMenuView mnuStart = (myMenuView) findViewById(R.id.mnu_star);
			mnuStart.setVisibility(View.INVISIBLE);

			// Get local Bluetooth adapter
			mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

			// If the adapter is null, then Bluetooth is not supported
			if (mBluetoothAdapter == null) {
				Toast.makeText(this, "Bluetooth is not available",
						Toast.LENGTH_LONG).show();
				finish();
				return;
			}
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater mi = getMenuInflater();
		mi.inflate(R.menu.menu_caro_activity, menu);

		// if(myCaroGame.getPlayer() == Player.BLUE){
		// menu.getItem(R.id.menu_search_device).setVisible(true);
		// menu.getItem(R.id.menu_discoverable).setVisible(true);
		// }

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_restart:
			initNewGame();
			return true;

		case R.id.menu_defautdiplay:
			mCaroView.setDefaulEgde();
			mCaroView.invalidate();
			return true;

		case R.id.menu_discoverable:
			ensureDiscoverable();

			return true;

		case R.id.menu_search_device:
			// Launch the DeviceListActivity to see devices and do scan
			Intent serverIntent = new Intent(this, myDeviceListActivity.class);
			startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
			return true;
		default:
			break;
		}
		return false;
	}

	public void initNewGame() {

		mCaroView.setAllowDraw(true);
		mCaroView.init();
		mCaroView.setFocusableInTouchMode(true);
		mCaroView.mCaroGame.NewGame();

	}
}
